﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;

using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Interop.Outlook;
 
using Ionic.Zip;
using MAPIConcubine;


namespace pstToRepos
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Outlook.Application outlookApplication = new Outlook.Application();

            // get the namespace object
            Outlook.NameSpace olNamespace = outlookApplication.GetNamespace("MAPI");

            // Logon to Session, here we use an already opened Outlook
            // olNamespace.Logon(missiing, missing, true, true);
            olNamespace.Logon("elookinto", "elookinto", false, true);
            MAPIConcubine.Fabric fabric = new MAPIConcubine.Fabric();
            try
            {

                String pst = @"c:\temp\joe2.pst";
                if (args.Length > 0)
                    pst = args[0];
                Store addedStore = null;
                Boolean exsiting = false;
                //Check there is a store with the same name alreay there ---
                foreach (Store store in olNamespace.Stores)
                {
                    if (store.FilePath != null && store.FilePath.Equals(pst))
                    {
                        addedStore = store;
                        exsiting = true;
                        break;
                    }
                }
                if (addedStore == null)
                {
                    olNamespace.AddStore(pst);

                    foreach (Store store in olNamespace.Stores)
                    {
                        if (store.FilePath != null && store.FilePath.Equals(pst))
                        {
                            addedStore = store;
                            break;
                        }
                    }
                }

                Outlook.MAPIFolder pstFolder = addedStore.GetRootFolder();
                ExtractItems(null, pstFolder, fabric);
                if (!exsiting)
                {
                    olNamespace.RemoveStore(pstFolder);
                }
                pstFolder = null;

            }
            catch (System.Runtime.InteropServices.COMException ee)
            {
                Console.WriteLine(ee.Message);
            }
            // that's all
            fabric = null;
            // logoff from namespace (session)
            olNamespace.Logoff();

            //release reference o outlook object
            outlookApplication = null;

            // Let the Garbagecollector do his work 
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }



        static private void ExtractItems(List<MailItem> mailItems, MAPIFolder folder, MAPIConcubine.Fabric fabric)
        {
            Items items = folder.Items;

            int itemcount = items.Count;

            foreach (object item in items)
            {
                if (item is MailItem)
                {
                    MailItem mailItem = item as MailItem;

                    Outlook.MailItem someMail = item as Outlook.MailItem;
                    if (someMail != null)
                    {
 
                        Dictionary<String, Object> hash = fabric.ReadSecureData(someMail.MAPIOBJECT);
                        String tempDir = Path.GetTempPath();
                        DirectoryInfo path = Directory.CreateDirectory(Path.Combine(tempDir, someMail.ConversationID));
                        StringBuilder sb = new StringBuilder();
                        sb.Append("subject=").Append(someMail.Subject);
                        sb.Append("\r\n");
                        sb.Append("message-id=").Append(someMail.ConversationID);
                        sb.Append("\r\n");
                        //sb.Append("content-id=").Append(someMail.
                        //sb.Append("language=").Append(someMail.
                        sb.Append("sent=").Append(someMail.SentOn.ToLongDateString());
                        sb.Append("\r\n");
                        sb.Append("received=").Append(someMail.ReceivedTime.ToLongDateString());
                        //  .Append(" ").Append(someMail.ReceivedTime.Kind);
                        sb.Append("\r\n");
                        sb.Append("from=").Append(hash["from"]);
                        sb.Append("\r\n");
                        sb.Append("to=").Append(hash["to"]);
                        sb.Append("\r\n");
                        sb.Append("cc=").Append(hash["cc"]);
                        sb.Append("\r\n");
                        sb.Append("bcc=").Append(hash["bcc"]);
                        sb.Append("\r\n");
                        //sb.Append("reply-to=").Append(hash["reply-to"]);
                        //sb.Append("\n");
                        sb.Append("senderName=").Append(hash["senderName"]);
                        sb.Append("\r\n");
                        Console.WriteLine(sb.ToString());

                        String metaFile = Path.Combine(path.FullName, "meta.txt");
                        String bodyText = hash["fbody"].ToString();

                        String bodyFile = Path.Combine(path.FullName, "message.txt");
                        if (bodyText.StartsWith(@"{\rtf"))
                            bodyFile = Path.Combine(path.FullName, "message.rtf");
                        else if (bodyText.StartsWith(@"<html"))
                            bodyFile = Path.Combine(path.FullName, "message.html");
                        File.WriteAllText(metaFile, sb.ToString());
                        File.WriteAllText(bodyFile, bodyText);
                        // MessageBox.Show(ss);
                        for (int i = 1; i <= someMail.Attachments.Count; i++)
                        {
                            String fileName = Path.Combine(path.FullName, someMail.Attachments[i].FileName);
                            someMail.Attachments[i].SaveAsFile(fileName);
                        }
                        String zipFileName = Path.GetTempPath() + "\\" + someMail.ConversationID + ".zip";
                        FileInfo fi = new FileInfo(zipFileName);
                        if (fi.Exists) fi.Delete();
                        ZipFile zf = new ZipFile(zipFileName);

                        zf.AddDirectory(path.FullName);
                        zf.Save();
                        wc.UploadFile("http://localhost:9080/ilookinto/my/uploadMessage.jsp", zipFileName);
                        path.Delete(true);
                        someMail = null;
                    }
                     
                }

            }

            foreach (Folder subfolder in folder.Folders)
            {
                ExtractItems(null, subfolder, fabric);
            }

        }

        static WebClient wc = new WebClient();

    }
}
